// if no last second score, will return NaN or 0 ?
export function lastScore(ns: number[], l: number = 1) {
  return ns.length > (l - 1) ? ns[ns.length - l] : 0
}

function handleNumber(scoreStack: number[], n: number) {
  if (Number.isSafeInteger(n) && n > -30000 && n < 30000) scoreStack.push(n)
}

const fnCalcMap: any = {
  'C': (scoreStack: number[]) => scoreStack.pop(),
  'D': (scoreStack: number[]) => handleNumber(scoreStack, lastScore(scoreStack) * 2),
  '+': (scoreStack: number[]) => handleNumber(scoreStack, lastScore(scoreStack) + lastScore(scoreStack, 2))
}

function calcScore(scoreStack: number[], currentScore: string) {
  const fnCalc: any = fnCalcMap[currentScore]
  fnCalc ? fnCalc(scoreStack) : handleNumber(scoreStack, parseInt(currentScore))
  return scoreStack
}

export function sumInts(ints: number[]) {
  return (ints.length < 1) ? 0 : ints.reduce((a, b) => a + b)
}

/**
 * Sum all score record
 * Example:
 *  softballSum(['5', '2', 'C', 'D', '+']) === 30
 *  softballSum(['5', '-2', '4', 'C', 'D', '9', '+', '+']) === 27
 * @param scores record array, like ['5', '2', 'C', 'D', '+']
 * @returns result sum scores
 */
export function softballSum(scores: string[]): number {
  const intScores = scores.reduce((numScores: number[], b) => {
    // console.debug(numScores, b, i, as)
    return calcScore(numScores, b)
  }, [])
  return sumInts(intScores)
}
